package com.pdstudio.charts;

import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.pdstudio.app.Application;
import com.pdstudio.bean.StationState;
import com.pdstudio.http.StationHttpMethod;
import com.pdstudio.weather.NewStationListStateActivity;
import com.pdstudio.weather.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class StationCurrentStateActivity extends Activity {

	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;
	BitmapDescriptor mCurrentMarker;

	MapView mMapView;
	BaiduMap mBaiduMap;

	// UI相关
	OnCheckedChangeListener radioButtonListener;
	Button requestLocButton;
	boolean isFirstLoc = true;// 是否首次定位
	
	Button stationListButton;//查看列表button

	private Handler handler = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chart_station_state_main);

		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					List<StationState> wds = null;
					if (msg.obj != null) {
						try {
							wds = (List<StationState>) msg.obj;
							SetStationStatesAdapter(wds);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		};

		/*
		 * requestLocButton = (Button) findViewById(R.id.button1); mCurrentMode
		 * = LocationMode.NORMAL; requestLocButton.setText("普通");
		 * OnClickListener btnClickListener = new OnClickListener() { public
		 * void onClick(View v) { switch (mCurrentMode) { case NORMAL:
		 * requestLocButton.setText("跟随"); mCurrentMode =
		 * LocationMode.FOLLOWING; mBaiduMap .setMyLocationConfigeration(new
		 * MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); break;
		 * case COMPASS: requestLocButton.setText("普通"); mCurrentMode =
		 * LocationMode.NORMAL; mBaiduMap .setMyLocationConfigeration(new
		 * MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); break;
		 * case FOLLOWING: requestLocButton.setText("罗盘"); mCurrentMode =
		 * LocationMode.COMPASS; mBaiduMap .setMyLocationConfigeration(new
		 * MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); break;
		 * } } }; requestLocButton.setOnClickListener(btnClickListener);
		 */
		/*
		 * RadioGroup group = (RadioGroup) this.findViewById(R.id.radioGroup);
		 * radioButtonListener = new OnCheckedChangeListener() {
		 * 
		 * @Override public void onCheckedChanged(RadioGroup group, int
		 * checkedId) { if (checkedId == R.id.defaulticon) { // 传入null则，恢复默认图标
		 * mCurrentMarker = null; mBaiduMap .setMyLocationConfigeration(new
		 * MyLocationConfiguration( mCurrentMode, true, null)); } if (checkedId
		 * == R.id.customicon) { // 修改为自定义marker mCurrentMarker =
		 * BitmapDescriptorFactory .fromResource(R.drawable.bb2); mBaiduMap
		 * .setMyLocationConfigeration(new MyLocationConfiguration(
		 * mCurrentMode, true, mCurrentMarker)); } } };
		 * group.setOnCheckedChangeListener(radioButtonListener);
		 */

		stationListButton=(Button)findViewById(R.id.chart_staion_list);
		stationListButton.setText("查看站点列表");
		stationListButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Intent intent=new Intent(StationCurrentStateActivity.this,StationListStateActivity.class);
				Intent intent = new Intent(StationCurrentStateActivity.this,NewStationListStateActivity.class);
				startActivity(intent);
			}});
		
		// 地图初始化
		mMapView = (MapView) findViewById(R.id.chart_station_state_bdmap);
		mBaiduMap = mMapView.getMap();
		// 开启定位图层
		//mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化
		//mLocClient = new LocationClient(getApplicationContext());// 20141028初始化locationclient的时候本来要传入this的，但是发现定位不成功，于是改成getapplicationcontext()就好了，也不知道为何
		//mLocClient.registerLocationListener(myListener);
		//LocationClientOption option = new LocationClientOption();
		//option.setOpenGps(true);// 打开gps
		//option.setCoorType("bd09ll"); // 设置坐标类型
		//option.setScanSpan(1000);
		//mLocClient.setLocOption(option);
		//mLocClient.start();

		// 界面加载时添加绘制图层
		// addCustomElementsDemo();
		
		//设定中心点坐标 

        LatLng cenpt = new LatLng(29.36063,113.09578); 
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
        .target(cenpt)
        .zoom(9)
        .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);

		Thread thread = new Thread() {
			@Override
			public void run() {
				try {
					StationHttpMethod shm = new StationHttpMethod(
							StationCurrentStateActivity.this);
					List<StationState> si = shm.GetStationStates(Application.getInstance().getSharePreferenceUtil().getAuthCode(), Application.getInstance().getCurSimpleCity().cityCode,
							Application.getInstance().getCurSimpleCity().cityCode, "2014-11-3-4");
					if (si != null) {
						Message m = handler.obtainMessage(0, si);
						handler.sendMessage(m);
					}
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), "网络异常，稍后重试！", 0)
							.show();
				}
			}
		};
		thread.start();
	}

	private void SetStationStatesAdapter(List<StationState> si) {
		if (si != null) {
			for (int i = 0; i < si.size(); i++) {
				try {
					StationState ss = new StationState();
					ss.address = si.get(i).address;
					ss.lat = si.get(i).lat;
					ss.lon = si.get(i).lon;
					ss.precipitation = si.get(i).precipitation;
					ss.temperature = si.get(i).temperature;
					ss.wind = si.get(i).wind;
					ss.windDirection = si.get(i).windDirection;

					double latd = 0;
					double lond = 0;
					try {
						latd = Double.valueOf(ss.lat);
						lond = Double.valueOf(ss.lon);
					} catch (Exception e) {
						e.printStackTrace();
					}

					float rote = 0;
					try {
						rote = Float.parseFloat(ss.windDirection);
					} catch (Exception e) {
						e.printStackTrace();
					}

					// 定义Maker坐标点
					LatLng point = new LatLng(latd, lond);
					// 构建Marker图标
					BitmapDescriptor bitmap = BitmapDescriptorFactory
							.fromResource(R.drawable.winddirect);
					// 构建MarkerOption，用于在地图上添加Marker
					OverlayOptions option = new MarkerOptions().position(point)
							.rotate(0).icon(bitmap);
					// 在地图上添加Marker，并显示
					// 将marker添加到地图上
					Marker marker = (Marker) (mBaiduMap.addOverlay(option));
					// 将信息写入marker
					Bundle bundle = new Bundle();
					bundle.putSerializable("info", ss);
					marker.setExtraInfo(bundle);

					// 添加文字
//					LatLng point1 = new LatLng(latd, lond + 0.0002);
//					OverlayOptions ooText = new TextOptions().bgColor(0x009ACD)
//							.fontSize(26).fontColor(0xFFFFFFFF)
//							.text(ss.temperature+"℃").rotate(0).position(point1);
//					mBaiduMap.addOverlay(ooText);

					// 添加标志物弹出框
					mBaiduMap
							.setOnMarkerClickListener(new OnMarkerClickListener() {
								@Override
								public boolean onMarkerClick(final Marker marker) {
									// 获得marker中的数据
									StationState info = (StationState) marker
											.getExtraInfo().get("info");

									InfoWindow mInfoWindow;
									// TODO Auto-generated method stub
									View view = LayoutInflater.from(
											getApplicationContext()).inflate(
											R.layout.baidu_map_stationstate,
											null);
									view.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											mBaiduMap.hideInfoWindow();
										}

									});
									TextView address = (TextView) view
											.findViewById(R.id.baidumap_stationsta_address);
									address.setText("地址：" + info.address);
									TextView temper = (TextView) view
											.findViewById(R.id.baidumap_stationsta_tempare);
									temper.setText("温度：" + info.temperature);
									TextView pricp = (TextView) view
											.findViewById(R.id.baidumap_stationsta_pricip);
									pricp.setText("降水：" + info.precipitation);
									TextView wind = (TextView) view
											.findViewById(R.id.baidumap_stationsta_wind);
									wind.setText("风速：" + info.wind);
									TextView windd = (TextView) view
											.findViewById(R.id.baidumap_stationsta_winddre);
									windd.setText("风向：" + info.windDirection);
									TextView lon = (TextView) view
											.findViewById(R.id.baidumap_stationsta_lon);
									lon.setText("经度：" + info.lon);
									TextView lat = (TextView) view
											.findViewById(R.id.baidumap_stationsta_lat);
									lat.setText("纬度：" + info.lat);
									final LatLng ll = marker.getPosition();
									Point p = mBaiduMap.getProjection()
											.toScreenLocation(ll);
									p.y -= 80;
									p.x-=30;
									LatLng llInfo = mBaiduMap.getProjection()
											.fromScreenLocation(p);
									// 先隐藏弹出的infowindow
									mBaiduMap.hideInfoWindow();

									mInfoWindow = new InfoWindow(view, llInfo,
											0);
									MapStatusUpdate m = MapStatusUpdateFactory
											.newLatLng(ll);
									mBaiduMap.setMapStatus(m);
									mBaiduMap.showInfoWindow(mInfoWindow);
									return true;
								}
							});

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 添加点、线、多边形、圆、文字
	 */
	public void addCustomElementsDemo() {

		StationState ss = new StationState();
		ss.address = "长沙";
		ss.lat = "39.963175";
		ss.lon = "116.400244";
		ss.precipitation = "100";
		ss.temperature = "10";
		ss.wind = "100";
		ss.windDirection = "90";

		// 定义Maker坐标点
		LatLng point = new LatLng(39.963175, 116.400244);
		// 构建Marker图标
		BitmapDescriptor bitmap = BitmapDescriptorFactory
				.fromResource(R.drawable.icon_windarrow);
		// 构建MarkerOption，用于在地图上添加Marker
		OverlayOptions option = new MarkerOptions().rotate(90).position(point)
				.icon(bitmap);
		// 在地图上添加Marker，并显示
		// 将marker添加到地图上
		Marker marker = (Marker) (mBaiduMap.addOverlay(option));
		// 将信息写入marker
		Bundle bundle = new Bundle();
		bundle.putSerializable("info", ss);
		marker.setExtraInfo(bundle);

		// 添加文字
		LatLng point1 = new LatLng(39.963175 + 0.000005, 116.400244);
		OverlayOptions ooText = new TextOptions().bgColor(0xAAFFFF00)
				.fontSize(24).fontColor(0xFFFF00FF).text(ss.address).rotate(0)
				.position(point1);
		mBaiduMap.addOverlay(ooText);

		// 添加标志物弹出框
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(final Marker marker) {
				// 获得marker中的数据
				StationState info = (StationState) marker.getExtraInfo().get(
						"info");

				InfoWindow mInfoWindow;
				// TODO Auto-generated method stub
				View view = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.baidu_map_stationstate, null);
				view.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mBaiduMap.hideInfoWindow();
					}

				});
				TextView address = (TextView) view
						.findViewById(R.id.baidumap_stationsta_address);
				address.setText(info.address);
				TextView temper = (TextView) view
						.findViewById(R.id.baidumap_stationsta_tempare);
				temper.setText(info.temperature);
				TextView pricp = (TextView) view
						.findViewById(R.id.baidumap_stationsta_pricip);
				pricp.setText(info.precipitation);
				TextView wind = (TextView) view
						.findViewById(R.id.baidumap_stationsta_wind);
				wind.setText(info.wind);
				TextView windd = (TextView) view
						.findViewById(R.id.baidumap_stationsta_winddre);
				windd.setText(info.windDirection);
				TextView lon = (TextView) view
						.findViewById(R.id.baidumap_stationsta_lon);
				lon.setText(info.lon);
				TextView lat = (TextView) view
						.findViewById(R.id.baidumap_stationsta_lat);
				lat.setText(info.lat);
				final LatLng ll = marker.getPosition();
				Point p = mBaiduMap.getProjection().toScreenLocation(ll);
				p.y -= 47;
				LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
				// 先隐藏弹出的infowindow
				mBaiduMap.hideInfoWindow();

				mInfoWindow = new InfoWindow(view, llInfo, 0);
				MapStatusUpdate m = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.setMapStatus(m);
				mBaiduMap.showInfoWindow(mInfoWindow);
				return true;
			}
		});

		/*
		 * 有异常不能用 TextView
		 * addr=(TextView)findViewById(R.id.baidumap_stationsta_address);
		 * addr.setText("临湘"); TextView
		 * tempr=(TextView)findViewById(R.id.baidumap_stationsta_tempare);
		 * tempr.setText("温度：13"); TextView
		 * preci=(TextView)findViewById(R.id.baidumap_stationsta_pricip);
		 * preci.setText("湿度：1"); TextView
		 * wind=(TextView)findViewById(R.id.baidumap_stationsta_wind);
		 * wind.setText("风速：130m/s"); TextView
		 * winddr=(TextView)findViewById(R.id.baidumap_stationsta_winddre);
		 * winddr.setText("风向：90"); TextView
		 * lon=(TextView)findViewById(R.id.baidumap_stationsta_lon);
		 * lon.setText("精度：111"); TextView
		 * lat=(TextView)findViewById(R.id.baidumap_stationsta_lat);
		 * lat.setText("纬度：133"); LatLng llText = new LatLng(39.86923,
		 * 116.397428); // 创建InfoWindow View
		 * v=this.findViewById(R.layout.baidu_map_stationstate); InfoWindow
		 * mInfoWindow = new InfoWindow(v, llText, 0); // 显示InfoWindow
		 * mBaiduMap.showInfoWindow(mInfoWindow);
		 */

		/*
		 * 下面注释的是百度地图例子中的代码 // 添加折线 LatLng p1 = new LatLng(39.97923,
		 * 116.357428); LatLng p2 = new LatLng(39.94923, 116.397428); LatLng p3
		 * = new LatLng(39.97923, 116.437428); List<LatLng> points = new
		 * ArrayList<LatLng>(); points.add(p1); points.add(p2); points.add(p3);
		 * OverlayOptions ooPolyline = new PolylineOptions().width(10)
		 * .color(0xAAFF0000).points(points); mBaiduMap.addOverlay(ooPolyline);
		 * // 添加弧线 OverlayOptions ooArc = new
		 * ArcOptions().color(0xAA00FF00).width(4) .points(p1, p2, p3);
		 * mBaiduMap.addOverlay(ooArc); // 添加圆 LatLng llCircle = new
		 * LatLng(39.90923, 116.447428); OverlayOptions ooCircle = new
		 * CircleOptions().fillColor(0x000000FF) .center(llCircle).stroke(new
		 * Stroke(5, 0xAA000000)) .radius(1400); mBaiduMap.addOverlay(ooCircle);
		 * 
		 * LatLng llDot = new LatLng(39.98923, 116.397428); OverlayOptions ooDot
		 * = new DotOptions().center(llDot).radius(6) .color(0xFF0000FF);
		 * mBaiduMap.addOverlay(ooDot); // 添加多边形 LatLng pt1 = new
		 * LatLng(39.93923, 116.357428); LatLng pt2 = new LatLng(39.91923,
		 * 116.327428); LatLng pt3 = new LatLng(39.89923, 116.347428); LatLng
		 * pt4 = new LatLng(39.89923, 116.367428); LatLng pt5 = new
		 * LatLng(39.91923, 116.387428); List<LatLng> pts = new
		 * ArrayList<LatLng>(); pts.add(pt1); pts.add(pt2); pts.add(pt3);
		 * pts.add(pt4); pts.add(pt5); OverlayOptions ooPolygon = new
		 * PolygonOptions().points(pts) .stroke(new Stroke(5,
		 * 0xAA00FF00)).fillColor(0xAAFFFF00); mBaiduMap.addOverlay(ooPolygon);
		 * // 添加文字 LatLng llText = new LatLng(39.86923, 116.397428);
		 * OverlayOptions ooText = new TextOptions().bgColor(0xAAFFFF00)
		 * .fontSize(24).fontColor(0xFFFF00FF).text("百度地图SDK").rotate(-30)
		 * .position(llText); mBaiduMap.addOverlay(ooText);
		 */
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		try{
			// 退出时销毁定位
			mLocClient.stop();
			// 关闭定位图层
			mBaiduMap.setMyLocationEnabled(false);
			mMapView.onDestroy();
			mMapView = null;	
		}catch(Exception e){e.printStackTrace();}
		super.onDestroy();
	}

}
